import 字段包.UserBean;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
doGet(request,response);
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        UserDao userDao = new UserDao();
        //获取当前登录用户信息
        UserBean userBean = (UserBean) request.getSession().getAttribute("user");//改动
        Integer createdBy  = UserBean.getId();//////WARNING
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //1.获取请求参数，封装到UserBean
        Date birthday   =null;
        try {
            birthday =sdf.parse(request.getParameter("birthday"));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        UserBean tmp = new UserBean();
        Date creationDate = new Date();
        tmp.setUserName(request.getParameter("userName"));
        tmp.getUserPassword(request.getParameter("userPassword"));
        tmp.setUserCode(request.getParameter("userCode"));;
        tmp.setGender(Integer.parseInt(request.getParameter("gender")));
        tmp.setUserRole(Integer.parseInt(request.getParameter("userRole")));
        tmp.setPhone(request.getParameter("phone"));
        tmp.setAddress(request.getParameter("address"));
        tmp.setBirthday(birthday);
        tmp.setCreatedDate(creationDate);
        tmp.setCreatedBy(createdBy);
        //改动

        //2.调用dao，进行注册
        Integer result = userDao.addUser(tmp);
        if (result >  0 ){
            //3。注册成功，跳转登录
            response.sendRedirect("/login.jsp");
        }else{
            //4.注册失败，重新注册
            request.setAttribute("msg","注册失败");
            request.getRequestDispatcher("/register.jsp").forward(request,response);
        }

    }
}
